//
//  UIViewController+Extensions.swift
//  DaRings
//
//  Created by 尹琼 on 2022/11/28.
//

import Foundation
import UIKit



extension UIViewController {
    
    public static func rootViewController() ->UIViewController? {
        
        var window = UIApplication.shared.keyWindow
        if window?.windowLevel != UIWindow.Level.normal{
            
            let windows = UIApplication.shared.windows
            
            for windowTemp in windows {
                if windowTemp.windowLevel == UIWindow.Level.normal{
                    window = windowTemp
                    break
                }
            }
        }
        let vc = window?.rootViewController
        
        return vc
    }
    
    public static func currentViewController() -> UIViewController? {
        let vc = rootViewController()
        return currentViewController(vc)
    }
    
    
    fileprivate static func currentViewController(_ vc :UIViewController?) -> UIViewController? {
        
        guard let vc = vc else {
            return nil
        }
        
        if let presentVC = vc.presentedViewController {
            return currentViewController(presentVC)
            
        } else if let tabVC = vc as? UITabBarController {
            
            if let selectVC = tabVC.selectedViewController {
                return currentViewController(selectVC)
            }
            
            return nil
        } else if let naiVC = vc as? UINavigationController {
            
            return currentViewController(naiVC.visibleViewController)
            
        } else {
            
            return vc
            
        }
    }
    
}

extension UIViewController {
    
    public func add(_ childController: UIViewController, toView: UIView?) {
        
        childController.beginAppearanceTransition(true, animated: false)
        self.addChild(childController)
        toView?.addSubview(childController.view)
        childController.endAppearanceTransition()
        childController.didMove(toParent: self)
        
        
    }
    
    public  func remove(_ childController: UIViewController) {
        childController.willMove(toParent: nil)
        childController.beginAppearanceTransition(true, animated: false)
        childController.view.removeFromSuperview()
        childController.removeFromParent()
        childController.endAppearanceTransition()
        
        
    }
    
}
